package utils;

import java.sql.*;

public class DBUtil {
    //1.定义数据库地址，用户名，密码，utf8编码
   public static final String URL="jdbc:mysql:///attdb?useSSL=false&characterEncoding=utf8";
   public static final String USER="root";
   public static final String PSW="root";
    //2.注册驱动
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    //3.获取连接对象
    public static Connection getConn() {
        Connection conn;
        try {
            conn = DriverManager.getConnection(URL, USER, PSW);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    //4.通用的查询方法
    public static ResultSet query(String sql,Object... keys){
        //1.获取连接对象
        Connection conn = getConn();
        //2.获取执行sql语句的对象
        ResultSet rs = null;
        try {
            PreparedStatement prs = conn.prepareStatement(sql);
            //2.5遍历数组，将数据赋值给每个？
            for (int i = 0; i < keys.length; i++) {
                prs.setObject((i+1),keys[i]);
            }
            //3.得到并返回结果集
            rs = prs.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return rs;
    }

    //5.通用的update方法
    public static int update(String sql,Object... keys){
        //1.获取连接对象
        Connection conn = getConn();
        //2.获取执行sql语句的对象
        int num=0;
        try {
            PreparedStatement prs = conn.prepareStatement(sql);
            //2.5遍历数组，将数据赋值给每个？
            for (int i = 0; i < keys.length; i++) {
                prs.setObject((i+1),keys[i]);
            }
            //3.得到并返回结果集
            num = prs.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return num;
    }
}
